package com.canal.display.config;

import com.canal.display.filter.LoginUserPasswordBodyFilter;
import com.canal.display.handler.LoginFailureHandler;
import com.canal.display.handler.LoginSuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;

/**
 * @author Administrator
 * @description
 * @date 2019年03月17 10:34
 */
public class JsonLoginConfigurer<T extends JsonLoginConfigurer<T,B>,B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T,B>{

    private LoginUserPasswordBodyFilter loginFilter;

    public JsonLoginConfigurer() {
        this.loginFilter = new LoginUserPasswordBodyFilter();
    }

    @Override
    public void configure(B builder) throws Exception {
        //设置Filter使用的AuthenticationManager,这里取公共的即可
        loginFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        //设置失败的Handler
        loginFilter.setAuthenticationFailureHandler(new LoginFailureHandler());
        //不将认证后的context放入session
        loginFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
        LoginUserPasswordBodyFilter filter = postProcess(loginFilter);
        builder.addFilterAfter(filter, LogoutFilter.class);
    }

    /**
     * 设置成功的Handler，这个handler定义成Bean，所以从外面set进来
     * @param loginSuccessHandler
     * @return
     */
    public JsonLoginConfigurer<T,B> loginSuccessHandler(LoginSuccessHandler loginSuccessHandler) {
        loginFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        return this;
    }
}
